package com.allenkerr.service;

import com.allenkerr.enums.ResultEnum;
import com.allenkerr.exception.GirlException;
import com.allenkerr.model.Girl;
import com.allenkerr.dao.GirlRepository;
import com.allenkerr.util.ResultUtils;
import com.allenkerr.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * Created by 小柯(Allen Kerr) on 17.6.4 11:05.
 */
@Service
public class GirlService {
    @Autowired
    private GirlRepository girlRepository;

    @Transactional  //开启事务支持
    public List<Girl> saveTwoGirls(Girl girlA, Girl girlB) {
        Girl girlAInDB = girlRepository.save(girlA);

        //异常
//        int i = 1 / 0;

        Girl girlBInDB = girlRepository.save(girlB);
        return Arrays.asList(girlAInDB, girlBInDB);
    }

    /**
     * 根据id获取女生的年龄，如果小于12岁，返回“上小学”，如果大于12岁并小于16岁，返回“上初中”
     *
     * @param id
     * @return
     */
    public Result getAgeById(Integer id) throws Exception {
        //抛出异常
//        int i = 1 / 0;

        Girl girl = girlRepository.findOne(id);

        if (girl.getAge() <= 12)
            //你还在上小学吧？code = 100
//            throw new Exception("你还在上小学吧？");
            throw new GirlException(ResultEnum.PRIMARY_SCHOOL);

        if (girl.getAge() <= 16)
            //你还在上初中吧？code = 101
//            throw new Exception("你还在上初中吧？");
            throw new GirlException(ResultEnum.MIDDLE_SCHOOL);

        //正常
        return ResultUtils.success(girl.getAge());
    }

    public List<Girl> findAll() {
        return girlRepository.findAll();
    }

    public Girl findOne(Integer id) {
        return girlRepository.findOne(id);
    }
}
